package io.renren.modules.medical.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.*;
import io.renren.modules.medical.dao.PatientBasicInformationDao;
import io.renren.modules.medical.entity.*;
import io.renren.modules.medical.entity.history.DrugHistoryEntity;
import io.renren.modules.medical.entity.history.NonDrugHistoryEntity;
import io.renren.modules.medical.entity.history.OperationHistoryEntity;
import io.renren.modules.medical.entity.history.PreviousDiseaseHistoryEntity;
import io.renren.modules.medical.service.*;
import io.renren.modules.medical.vo.medicalVo.*;
import io.renren.modules.medical.vo.medicalVo.info.DiseaseMapVo;
import io.renren.modules.medical.vo.medicalVo.info.TreatmentInfoSaveVo;
import io.renren.modules.medical.vo.medicalVo.info.TreatmentMapVo;
import io.renren.modules.sys.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.invoke.LambdaConversionException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service("patientBasicInformationService")
public class PatientBasicInformationServiceImpl extends ServiceImpl<PatientBasicInformationDao, PatientBasicInformationEntity> implements PatientBasicInformationService {


    private final PatientInfoService patientInfoService;

    private final PatientDoctorRelativeService patientDoctorRelativeService;

    private final PatientDiseaseInformationService patientDiseaseInformationService;

    private final PatientTreatmentInformationService patientTreatmentInformationService;

    private final DrugHistoryService drugHistoryService;

    private final NonDrugHistoryService nonDrugHistoryService;

    private final OperationHistoryService operationHistoryService;

    private final DoctorInfoService doctorInfoService;

    private final PreviousDiseaseHistoryService previousDiseaseHistoryService;

    private final IllSubService illSubService;

    private final SysUserRoleService sysUserRoleService;

    /**
     * 前端分页展示用户信息
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<PatientBasicInformationEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 设置基础构造条件
        String key = (String) params.get("key");
        // 根据原有参数获取原有的HealthGuidanceEntity集合

        if (StringUtils.isNotEmpty(key) && StringUtils.isNumeric(key)) {
            // 添加患者id查询条件
            int length = key.length();
            Long numberKey = Long.valueOf(key);
            if (length <= 10) {
                // 输入的是患者id
                queryWrapper.eq(PatientBasicInformationEntity::getPatientInfoId, numberKey);
            } else {
                // 说明输入的是手机号码
                queryWrapper.eq(PatientBasicInformationEntity::getPhoneNumber, numberKey);
            }
        } else if (StringUtils.isNotEmpty(key)) {
            // 添加患者姓名查询条件
            queryWrapper.eq(PatientBasicInformationEntity::getName, key);
        }

        // 判断当前用户是医生还是管理员或者审核
        List<Long> roles = DoctorInfoUtils.getRole(sysUserRoleService);
        if ( roles.contains(Constant.SysRole.ADMIN.getValue()) ){
            // 访问全部
        }else if( roles.contains(Constant.SysRole.DOCTOR.getValue()) ){
            // 医生就只访问当前医生创建的
            DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
            queryWrapper.eq(PatientBasicInformationEntity::getDoctorId, doctorInfo.getId());
        }else{
            throw new MedicalException(HttpStatus.SC_FORBIDDEN, "用户无权访问健康指导列表");
        }


        // 根据修改时间排序
        queryWrapper.orderByDesc(BaseEntity::getUpdateTime);
        // 获取基础实体集合
        IPage<PatientBasicInformationEntity> page = this.page(
                new Query<PatientBasicInformationEntity>().getPage(params),
                queryWrapper
        );

        // 遍历封装
        List<PatientBasicInformationEntity> records = page.getRecords();
        List<PatientBasicListVo> newRecords = records.stream().map(item -> {
            PatientBasicListVo patientBasicListVo = new PatientBasicListVo();
            BeanUtils.copyProperties(item, patientBasicListVo);
            if (item.getSubId() != null) {
                IllSubEntity illSubEntity = illSubService.getById(item.getSubId());
                patientBasicListVo.setSubTitle(illSubEntity != null ? illSubEntity.getTitle() : "");
            }
            if (item.getDoctorId() != null){
                DoctorInfoEntity doctorInfoEntity = doctorInfoService.getById(item.getDoctorId());
                patientBasicListVo.setDoctorName(doctorInfoEntity != null ? doctorInfoEntity.getName() : "");
            }

            return patientBasicListVo;
        }).collect(Collectors.toList());

        Page<PatientBasicListVo> patientBasicListVoPage = new Page<>();
        BeanUtils.copyProperties(page, patientBasicListVoPage);
        patientBasicListVoPage.setRecords(newRecords);
        return new PageUtils(patientBasicListVoPage);
    }

    /**
     * 往要回显前端的数据中添加上七个历史信息
     */
    public void putTreatmentHistory(DiseaseInfoDetailVo diseaseInfoDetailVo) {
        // 先获取disease表的四个Id
        Long koaDrugHistoryId = diseaseInfoDetailVo.getKoaDrugHistoryId();
        Long koaNonDrugHistoryId = diseaseInfoDetailVo.getKoaNonDrugHistoryId();
        Long koaOperationHistoryId = diseaseInfoDetailVo.getKoaOperationHistoryId();
        Long previousHistoryId = diseaseInfoDetailVo.getPreviousHistoryId();
        Long drugTreatmentId = diseaseInfoDetailVo.getTreatmentInfo().getDrugTreatmentId();
        Long nonDrugTreatmentId = diseaseInfoDetailVo.getTreatmentInfo().getNonDrugTreatmentId();
        Long operationTreatmentId = diseaseInfoDetailVo.getTreatmentInfo().getOperationTreatmentId();
        diseaseInfoDetailVo.setTreatmentMap(new DiseaseMapVo());
        // 然后判定
        if (koaDrugHistoryId != null) {
            DrugHistoryEntity drugHistoryEntity = drugHistoryService.getById(koaDrugHistoryId);
            diseaseInfoDetailVo.getTreatmentMap().setKoaDrugHistory(drugHistoryEntity);
        }
        if (koaNonDrugHistoryId != null) {
            NonDrugHistoryEntity nonDrugHistoryEntity = nonDrugHistoryService.getById(koaNonDrugHistoryId);
            diseaseInfoDetailVo.getTreatmentMap().setKoaNonDrugHistory(nonDrugHistoryEntity);
        }
        if (koaOperationHistoryId != null) {
            OperationHistoryEntity operationHistoryEntity = operationHistoryService.getById(koaOperationHistoryId);
            diseaseInfoDetailVo.getTreatmentMap().setKoaOperationHistory(operationHistoryEntity);
        }
        if (previousHistoryId != null) {
            PreviousDiseaseHistoryEntity previousHistoryEntity = previousDiseaseHistoryService.getById(previousHistoryId);
            diseaseInfoDetailVo.getTreatmentMap().setPreviousHistory(previousHistoryEntity);
        }
        diseaseInfoDetailVo.getTreatmentInfo().setTreatmentMap(new TreatmentMapVo());
        if (drugTreatmentId != null) {
            DrugHistoryEntity drugHistoryEntity = drugHistoryService.getById(drugTreatmentId);
            diseaseInfoDetailVo.getTreatmentInfo().getTreatmentMap().setDrugTreatment(drugHistoryEntity);
        }
        if (nonDrugTreatmentId != null) {
            NonDrugHistoryEntity nonDrugHistoryEntity = nonDrugHistoryService.getById(nonDrugTreatmentId);
            diseaseInfoDetailVo.getTreatmentInfo().getTreatmentMap().setNonDrugTreatment(nonDrugHistoryEntity);
        }
        if (operationTreatmentId != null) {
            OperationHistoryEntity operationHistoryEntity = operationHistoryService.getById(operationTreatmentId);
            diseaseInfoDetailVo.getTreatmentInfo().getTreatmentMap().setOperationTreatment(operationHistoryEntity);
        }
    }

    /**
     * 获取用户详细信息，作用是前端查询用户详细信息展示
     */
    @Override
    public PatientBasicDetailVo getDetail(Long id) {
        PatientBasicInformationEntity basicInformationEntity = this.getById(id);
        if (basicInformationEntity == null) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "找不到病人基本信息");
        }
        PatientBasicDetailVo patientBasicDetailVo = new PatientBasicDetailVo();
        BeanUtils.copyProperties(basicInformationEntity, patientBasicDetailVo);
        // 根据basicId查询到subList
        LambdaQueryWrapper<PatientDoctorRelativeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, id);
        List<PatientDoctorRelativeEntity> relativeEntityList = patientDoctorRelativeService.list(queryWrapper);
        if (relativeEntityList.size() <= 0 || patientBasicDetailVo.getIsGonitis() == 0) {
            return patientBasicDetailVo;
        }
        // 进行大封装
        List<DiseaseInfoListItemVo> diseaseInfoListItemVos = relativeEntityList.stream().map(item -> {
            DiseaseInfoListItemVo diseaseInfoListItemVo = new DiseaseInfoListItemVo();
            BeanUtils.copyProperties(item, diseaseInfoListItemVo);
            // 1、先找到所有basicId和subId对应的disease集合
            LambdaQueryWrapper<PatientDiseaseInformationEntity> diseaseInfoWrapper = new LambdaQueryWrapper<>();
            diseaseInfoWrapper.eq(PatientDiseaseInformationEntity::getPatientBasicId, id);
            diseaseInfoWrapper.eq(PatientDiseaseInformationEntity::getKoaDescribeId, item.getSubId());
            // 进行排序
            diseaseInfoWrapper.orderByAsc(BaseEntity::getCreateTime);
            List<PatientDiseaseInformationEntity> patientDiseaseList = patientDiseaseInformationService.list(diseaseInfoWrapper);
            if (patientDiseaseList.size() <= 0) {
                return diseaseInfoListItemVo;
            }
            AtomicInteger createSort = new AtomicInteger(1);
            // 对patientDiseaseList进行遍历封装
            List<DiseaseInfoDetailVo> diseaseInfoDetailVos = patientDiseaseList.stream().map(diseaseItem -> {
                // 先拷贝到diseaseInfoDetailVo中
                DiseaseInfoDetailVo diseaseInfoDetailVo = new DiseaseInfoDetailVo();
                BeanUtils.copyProperties(diseaseItem, diseaseInfoDetailVo);
                diseaseInfoDetailVo.setCreateTimeDescribe("第" + ArabicToChineseConverterUtil.convertToChinese(createSort.get()) + "次诊断");
                createSort.addAndGet(1);
                // 封装进koaDescribe
                IllSubEntity illSubEntity = illSubService.getById(diseaseInfoDetailVo.getKoaDescribeId());
                diseaseInfoDetailVo.setKoaDescribe(illSubEntity.getLevelDescribe());
                // 再将treatment信息放入
                LambdaQueryWrapper<PatientTreatmentInformationEntity> patientTreatmentInfoWrapper = new LambdaQueryWrapper<>();
                patientTreatmentInfoWrapper.eq(PatientTreatmentInformationEntity::getPatientDiseaseId, diseaseInfoDetailVo.getId());
                PatientTreatmentInformationEntity treatmentInformationEntity = patientTreatmentInformationService.getOne(patientTreatmentInfoWrapper);
                // 再拷贝
                if (treatmentInformationEntity == null) {
                    treatmentInformationEntity = new PatientTreatmentInformationEntity();
                }
                TreatmentInfoSaveVo treatmentInfoSaveVo = new TreatmentInfoSaveVo();
                BeanUtils.copyProperties(treatmentInformationEntity, treatmentInfoSaveVo);
                // 拷贝完以后赋值给diseaseInfoDetailVo
                diseaseInfoDetailVo.setTreatmentInfo(treatmentInfoSaveVo);
                // 做完这些再将七个历史全部放入
                putTreatmentHistory(diseaseInfoDetailVo);
                return diseaseInfoDetailVo;
            }).collect(Collectors.toList());
            diseaseInfoListItemVo.setDiseaseInfos(diseaseInfoDetailVos);
            return diseaseInfoListItemVo;
        }).collect(Collectors.toList());
        patientBasicDetailVo.setDiseaseInfoList(diseaseInfoListItemVos);
        return patientBasicDetailVo;
    }

    /**
     * 保存basicInfo表信息
     */
    @Transactional
    @Override
    public Long saveBasicInfo(PatientBasicInformationEntity patientBasicInfo) {
        // 先找到病人对应的patient_doctor_relative表 sub_id和patient_id对应
        boolean isGonitis = DoctorInfoUtils.isGonitis(patientBasicInfo.getSubId(), illSubService);
        LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PatientDoctorRelativeEntity::getSubId, patientBasicInfo.getSubId());
        wrapper.eq(PatientDoctorRelativeEntity::getPatientId, patientBasicInfo.getPatientInfoId());
        PatientDoctorRelativeEntity patientDoctorRelativeEntity = patientDoctorRelativeService.getOne(wrapper);
        if (patientDoctorRelativeEntity == null) {
            // 如果没有对应的patientDoctorRelativeEntity
            throw new MedicalException(ResultCodeEnum.INFORMATION_INSERT_ERROR.getCode(), "找不到对应的病情关系");
        }
        PatientInfoEntity patientInfoEntity = patientInfoService.getById(patientDoctorRelativeEntity.getPatientId());
        patientBasicInfo.setName(patientInfoEntity.getName());
        patientBasicInfo.setDoctorId(DoctorInfoUtils.getDoctorInfo(doctorInfoService).getId());
        if (isGonitis) {
            patientBasicInfo.setIsGonitis(1);
        } else {
            patientBasicInfo.setIsGonitis(0);
        }
        this.save(patientBasicInfo);
        Long patientBasicInfoId = patientBasicInfo.getId();
        patientDoctorRelativeEntity.setPatientBasicId(patientBasicInfoId);
        patientDoctorRelativeService.updateById(patientDoctorRelativeEntity);
        if (isGonitis) {
            return patientBasicInfoId;
        } else {
            return -1L;
        }
    }

    /**
     * 得到用户完整的信息，作用修改用户信息时的回显
     */
    @Override
    public PatientBasicDetailVo getAllInformation(Long id) {
        LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorWrapper = new LambdaQueryWrapper<>();
        patientDoctorWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, id);
        List<PatientDoctorRelativeEntity> list = patientDoctorRelativeService.list(patientDoctorWrapper);
        if (list == null || list.size() <= 0) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "没有找到患者信息");
        }
        // 先查找到
        PatientBasicDetailVo allInformation = this.getDetail(id);
        PatientInfoEntity patientInfoEntity = patientInfoService.getById(allInformation.getPatientInfoId());
        PatientNameAndIdVo patientNameAndIdVo = new PatientNameAndIdVo();
        patientNameAndIdVo.setPatientId(patientInfoEntity.getId());
        patientNameAndIdVo.setPatientName(patientInfoEntity.getName());
        patientNameAndIdVo.setPatientPhone(patientInfoEntity.getPhone());
        ArrayList<PatientNameAndIdVo> patientInfoList = new ArrayList<>();
        patientInfoList.add(patientNameAndIdVo);
        allInformation.getParam().put("patientInfoList", patientInfoList);
        return allInformation;
    }

    /**
     * 获取到用户信息的AllList，作用是展示在前端供管理员选择性删除
     */
    @Override
    public List<InfoDeleteVo> getDeleteList(Long basicId) {
        ArrayList<InfoDeleteVo> resultList = new ArrayList<>();
        PatientBasicInformationEntity basicInfoEntity = this.getById(basicId);
        if (basicInfoEntity == null) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "未找到患者基本信息");
        }
        String name = basicInfoEntity.getName();
        InfoDeleteVo infoDeleteVo1 = new InfoDeleteVo();
        infoDeleteVo1.setId(basicId);
        infoDeleteVo1.setLabel("[" + name + "]患者基本信息");
        infoDeleteVo1.setLevel(1);
        // 获取第二层
        LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorWrapper = new LambdaQueryWrapper<>();
        patientDoctorWrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, basicId);
        List<PatientDoctorRelativeEntity> relativeEntityList = patientDoctorRelativeService.list(patientDoctorWrapper);
        if (relativeEntityList.size() <= 0) {
            resultList.add(infoDeleteVo1);
            return resultList;
        } else if (relativeEntityList.size() == 1) {
            PatientDoctorRelativeEntity patientDoctorRelativeEntity = relativeEntityList.get(0);
            IllSubEntity illSubEntity = illSubService.getById(patientDoctorRelativeEntity.getSubId());
            if (illSubEntity.getParentId() == 0 || basicInfoEntity.getIsGonitis() == 0) {
                resultList.add(infoDeleteVo1);
                return resultList;
            }
        }
        // 获取第二层
        List<InfoDeleteVo> twoLevelChildren = relativeEntityList.stream().map(item -> {
            Long id = item.getId();
            InfoDeleteVo infoDeleteVo2 = new InfoDeleteVo();
            infoDeleteVo2.setId(id);
            infoDeleteVo2.setLabel(item.getSubTitle());
            infoDeleteVo2.setLevel(2);
            LambdaQueryWrapper<PatientDiseaseInformationEntity> patientDiseaseInfoWrapper = new LambdaQueryWrapper<>();
            patientDiseaseInfoWrapper.eq(PatientDiseaseInformationEntity::getPatientBasicId, item.getPatientBasicId());
            patientDiseaseInfoWrapper.eq(PatientDiseaseInformationEntity::getKoaDescribeId, item.getSubId());
            patientDiseaseInfoWrapper.orderByAsc(BaseEntity::getCreateTime);
            List<PatientDiseaseInformationEntity> threeLevelList = patientDiseaseInformationService.list(patientDiseaseInfoWrapper);
            if (threeLevelList.size() <= 0) {
                return infoDeleteVo2;
            }
            AtomicInteger count = new AtomicInteger(1);
            // 获取第三层
            List<InfoDeleteVo> threeLevelChildren = threeLevelList.stream().map(obj -> {
                Long diseaseId = obj.getId();
                InfoDeleteVo infoDeleteVo3 = new InfoDeleteVo();
                infoDeleteVo3.setChildren(null);
                infoDeleteVo3.setId(diseaseId);
                infoDeleteVo3.setLabel("第" + ArabicToChineseConverterUtil.convertToChinese(count.get()) + "次诊断");
                infoDeleteVo3.setLevel(3);
                count.getAndIncrement();
                return infoDeleteVo3;
            }).collect(Collectors.toList());
            infoDeleteVo2.setChildren(threeLevelChildren);
            return infoDeleteVo2;
        }).collect(Collectors.toList());

        infoDeleteVo1.setChildren(twoLevelChildren);
        resultList.add(infoDeleteVo1);
        return resultList;
    }

    /**
     * 删除用户Info，适用于当前用户除了基础信息表还有其他信息在
     */
    @Transactional
    @Override
    public void removeInfo(InfoDeleteVo infoDeleteVo) {
        // 先获取到level
        Integer level = infoDeleteVo.getLevel();
        if (level == 1) {
            deleteBasic(infoDeleteVo.getId());
        }
        if (level == 3) {
            PatientDiseaseInformationEntity informationEntity = patientDiseaseInformationService.getById(infoDeleteVo.getId());
            if (informationEntity == null) {
                return;
            }
            // 删除后再判断当前的diseaseInfo是不是最后一个
            Long koaDescribeId = informationEntity.getKoaDescribeId();
            Long patientBasicId = informationEntity.getPatientBasicId();
            LambdaQueryWrapper<PatientDiseaseInformationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PatientDiseaseInformationEntity::getPatientBasicId, patientBasicId);
            wrapper.eq(PatientDiseaseInformationEntity::getKoaDescribeId, koaDescribeId);
            int count = patientDiseaseInformationService.count(wrapper);
            // 直接进行删除第三层的表信息
            removeThreeLevel(informationEntity);
            if (count > 1) {
                return;
            }
            // 看一看relativeEntity是不是只有一个
            LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(PatientDoctorRelativeEntity::getPatientBasicId, patientBasicId);
            List<PatientDoctorRelativeEntity> list = patientDoctorRelativeService.list(wrapper1);
            if (list.size() == 1) {
                // 直接修改subId和subTitle
                IllSubEntity illSubEntity = illSubService.getById(koaDescribeId);
                IllSubEntity parentSub = illSubService.getById(illSubEntity.getParentId());
                PatientDoctorRelativeEntity patientDoctorRelativeEntity = list.get(0);
                patientDoctorRelativeEntity.setSubTitle(parentSub.getTitle());
                patientDoctorRelativeEntity.setSubId(illSubEntity.getParentId());
                patientDoctorRelativeService.updateById(patientDoctorRelativeEntity);
                return;
            }
            // 反之就直接删除
            wrapper1.eq(PatientDoctorRelativeEntity::getSubId, koaDescribeId);
            patientDoctorRelativeService.remove(wrapper1);
        }
    }

    /**
     * 删除掉用户基本信息表，适用于当前用户只剩下基础信息
     *
     */
    @Transactional
    @Override
    public void deleteBasic(Long basicId) {
        // 先删除basic表，再删除关系表
        this.removeById(basicId);
        // 将所有关联该basicId表的关系表全部删除掉
        LambdaQueryWrapper<PatientDoctorRelativeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PatientDoctorRelativeEntity::getPatientBasicId, basicId);
        List<PatientDoctorRelativeEntity> list = patientDoctorRelativeService.list(wrapper);
        if (list == null || list.size() <= 0) {
            return;
        }
        list.forEach(item -> {
            item.setPatientBasicId(null);
            Long subId = item.getSubId();
            IllSubEntity illSubEntity = illSubService.getById(subId);
            if (illSubEntity.getParentId() != 0) {
                // 如果父级二级是那就直接更新
                IllSubEntity parentEntity = illSubService.getById(illSubEntity.getParentId());
                item.setSubTitle(parentEntity.getTitle());
                item.setSubId(parentEntity.getParentId());
                patientDoctorRelativeService.updateById(item);
            }
        });
    }

    /**
     * 微信端调查问卷获取用户普通信息
     *
     * @return patientNameAndIdVo
     */
    @Override
    public PatientNameAndIdVo getCommonInfo() {
        //TODO 等登陆模块做了再动态获取到userId
        Long patientId = 6L;

        // 1、获取到关系表集合，由于关系表patientInfoId对应的basicId唯一，直接list[0]获取basicId
        LambdaQueryWrapper<PatientBasicInformationEntity> patientBasicInfoWrapper = new LambdaQueryWrapper<>();
        patientBasicInfoWrapper.eq(PatientBasicInformationEntity::getPatientInfoId, patientId);
        List<PatientBasicInformationEntity> list = this.list(patientBasicInfoWrapper);
        if (list == null || list.size() <= 0) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "找不到患者基本信息");
        }
        PatientBasicInformationEntity basicInformationEntity = list.get(0);

        // 3、封装信息
        PatientNameAndIdVo patientNameAndIdVo = new PatientNameAndIdVo();
        patientNameAndIdVo.setPatientName(basicInformationEntity.getName());
        patientNameAndIdVo.setPatientId(patientId);
        patientNameAndIdVo.setIdNumber(basicInformationEntity.getIdNumber());
        patientNameAndIdVo.setPatientPhone(basicInformationEntity.getPhoneNumber());

        // 4、返回数据
        return patientNameAndIdVo;
    }

    /**
     * 通过basicId获取到sub集合
     */
    @Override
    public List<IllSubEntity> getSubsByBasicId(Long patientBasicInfoId) {
        PatientBasicInformationEntity patientBasicInfoEntity = this.getById(patientBasicInfoId);
        if (patientBasicInfoEntity == null) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "找不到患者基本信息");
        }
        IllSubEntity subEntity = illSubService.getById(patientBasicInfoEntity.getSubId());
        if (subEntity == null || subEntity.getParentId() == null) {
            throw new MedicalException(ResultCodeEnum.NOT_FIND_ERROR.getCode(), "找不到用户的病情信息");
        }
        Long subId;
        if (subEntity.getParentId().equals(0L)) {
            subId = patientBasicInfoEntity.getSubId();
        } else {
            subId = subEntity.getParentId();
        }
        return illSubService.getChildren(subId);
    }

    @Override
    public List<PatientNameAndIdVo> patients(Long subId) {
        LambdaQueryWrapper<PatientDoctorRelativeEntity> patientDoctorRelativeWrapper = new LambdaQueryWrapper<>();
        DoctorInfoEntity doctorInfo = DoctorInfoUtils.getDoctorInfo(doctorInfoService);
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getSubId, subId);
        patientDoctorRelativeWrapper.eq(PatientDoctorRelativeEntity::getDoctorId, doctorInfo.getId());
        List<PatientDoctorRelativeEntity> patients = patientDoctorRelativeService.list(patientDoctorRelativeWrapper);
        List<PatientNameAndIdVo> resultList = patients.stream().map(item -> {
            if (item.getPatientBasicId() != null && this.getById(item.getPatientBasicId()) != null) {
                return null;
            }
            PatientInfoEntity patientInfoEntity = patientInfoService.getById(item.getPatientId());
            PatientNameAndIdVo patientNameAndIdVo = new PatientNameAndIdVo();
            patientNameAndIdVo.setPatientName(patientInfoEntity.getName());
            patientNameAndIdVo.setPatientPhone(patientInfoEntity.getPhone());
            patientNameAndIdVo.setPatientId(patientInfoEntity.getId());
            return patientNameAndIdVo;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 删除第三层的用户信息，作用是删除掉basicInfo关联的diseaseInfo表
     */
    private void removeThreeLevel(PatientDiseaseInformationEntity informationEntity) {
        LambdaQueryWrapper<PatientTreatmentInformationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PatientTreatmentInformationEntity::getPatientDiseaseId, informationEntity.getId());
        PatientTreatmentInformationEntity treatmentInformationEntity = patientTreatmentInformationService.getOne(wrapper);
        if (treatmentInformationEntity != null) {
            // 把关联的三个历史表删除掉在直接删除治疗表
            Long drugTreatmentId = treatmentInformationEntity.getDrugTreatmentId();
            Long nonDrugTreatmentId = treatmentInformationEntity.getNonDrugTreatmentId();
            Long operationTreatmentId = treatmentInformationEntity.getOperationTreatmentId();
            if (drugTreatmentId != null) {
                drugHistoryService.removeById(drugTreatmentId);
            }
            if (nonDrugTreatmentId != null) {
                nonDrugHistoryService.removeById(nonDrugTreatmentId);
            }
            if (operationTreatmentId != null) {
                operationHistoryService.removeById(operationTreatmentId);
            }
            patientTreatmentInformationService.removeById(treatmentInformationEntity.getId());
        }
        Long koaDrugHistoryId = informationEntity.getKoaDrugHistoryId();
        Long koaNonDrugHistoryId = informationEntity.getKoaNonDrugHistoryId();
        Long koaOperationHistoryId = informationEntity.getKoaOperationHistoryId();
        Long previousHistoryId = informationEntity.getPreviousHistoryId();
        if (koaDrugHistoryId != null) {
            drugHistoryService.removeById(koaDrugHistoryId);
        }
        if (koaDrugHistoryId != null) {
            nonDrugHistoryService.removeById(koaNonDrugHistoryId);
        }
        if (koaOperationHistoryId != null) {
            operationHistoryService.removeById(koaOperationHistoryId);
        }
        if (previousHistoryId != null) {
            previousDiseaseHistoryService.removeById(previousHistoryId);
        }
        patientDiseaseInformationService.removeById(informationEntity.getId());
    }


}